﻿using System;
using System.Windows;
using System.Windows.Input;
using PersonaLibrary.Data;
using System.Linq;

namespace PersonaLibrary.ViewModel
{
    public class LinqEditableItem<TEntity, TView> : EditableItemViewModel<TEntity, TView>
        where TEntity : BaseEntity
        where TView : View.IView, new()
    {
    	private RelayCommand _refresh;
        protected LinqToDbDataContext Context = new LinqToDbDataContext();
		
		public RelayCommand RefreshCommand()
		{
			if(_refresh == null)
				_refresh = new RelayCommand(x => Refresh(), x => CanRefresh());

			return _refresh;
		}

		private void Refresh()
		{
			if(EditableItem.Id != 0)
			{
				EditableItem = Context.GetTable<TEntity>().Single(x => ((TEntity)x).Id == EditableItem.Id);
			}
		}

		private bool CanRefresh()
		{
			return EditableItem.Id != 0;
		}

        public override void Commit()
        {
            if(EditableItem != null && EditableItem.Id == 0) 
				Context.GetTable<TEntity>().InsertOnSubmit(EditableItem);
            Context.SubmitChanges();
            base.Commit();
        }

        public override void Dispose()
        {
            Context.Dispose();
        }

		protected override void OnViewCreated()
		{
			base.OnViewCreated();

			Keyboard.AddKeyDownHandler((DependencyObject)View, OnKeyDownHandler);
		}

		private void OnKeyDownHandler(object sender, KeyEventArgs e)
		{
			if(e.Key == Key.Enter)
			{
				if (CanCommit())
				{
					Action action = Commit;
					Dispatcher.BeginInvoke(action);
				}
			}
		}
    }
}
